#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
运行所有测试
Run All Tests

统一运行所有测试脚本的入口
Unified entry point for running all test scripts
"""

import os
import sys
import subprocess
import time
from datetime import datetime

def run_test(test_name, test_module):
    """运行单个测试"""
    print(f"\n{'='*60}")
    print(f"运行测试: {test_name}")
    print(f"{'='*60}")
    
    start_time = time.time()
    
    try:
        # 运行测试模块
        result = subprocess.run([
            sys.executable, '-m', test_module
        ], capture_output=True, text=True, cwd=os.getcwd(), encoding='utf-8')
        
        elapsed_time = time.time() - start_time
        
        if result.returncode == 0:
            print(f"✓ {test_name} 测试通过 ({elapsed_time:.2f}s)")
            if result.stdout:
                print(f"\n输出:\n{result.stdout}")
            return True
        else:
            print(f"✗ {test_name} 测试失败 ({elapsed_time:.2f}s)")
            if result.stdout:
                print(f"\n标准输出:\n{result.stdout}")
            if result.stderr:
                print(f"\n错误输出:\n{result.stderr}")
            return False
            
    except Exception as e:
        elapsed_time = time.time() - start_time
        print(f"✗ {test_name} 测试异常: {str(e)} ({elapsed_time:.2f}s)")
        return False

def main():
    """主函数"""
    print("医疗问答系统 - 所有测试运行器")
    print("=" * 60)
    print(f"开始时间: {datetime.now()}")
    print("=" * 60)
    
    # 定义测试列表
    tests = [
        ("基础功能测试", "tests.test_basic"),
        ("Neo4j知识图谱测试", "tests.test_neo4j_qa"),
        ("训练和推理测试", "tests.test_training"),
    ]
    
    # 运行所有测试
    results = []
    total_start_time = time.time()
    
    for test_name, test_module in tests:
        success = run_test(test_name, test_module)
        results.append((test_name, success))
    
    total_elapsed_time = time.time() - total_start_time
    
    # 显示总结
    print(f"\n{'='*60}")
    print("测试总结")
    print("=" * 60)
    
    passed = 0
    failed = 0
    
    for test_name, success in results:
        status_symbol = "✓" if success else "✗"
        status_text = "通过" if success else "失败"
        print(f"{status_symbol} {test_name:<20} {status_text}")
        
        if success:
            passed += 1
        else:
            failed += 1
    
    print("-" * 60)
    print(f"总计: {len(results)} 个测试套件")
    print(f"通过: {passed} 个")
    print(f"失败: {failed} 个")
    print(f"成功率: {passed/len(results)*100:.1f}%")
    print(f"总用时: {total_elapsed_time:.2f}s")
    print(f"结束时间: {datetime.now()}")
    
    # 提供建议
    print(f"\n{'='*60}")
    print("使用建议")
    print("=" * 60)
    
    if failed == 0:
        print("🎉 所有测试套件都通过了！")
        print("\n系统已经可以正常使用。")
        print("下一步可以：")
        print("  1. 启动应用: python app.py")
        print("  2. 运行训练: python train.py")
        print("  3. 查看文档: README.md")
    else:
        print("❌ 有部分测试失败，请检查：")
        print("  1. 确保所有依赖已安装")
        print("  2. 检查数据文件是否完整")
        print("  3. 查看具体错误信息")
        print("  4. 运行单个测试进行调试")
        print("\n单独运行测试的命令：")
        for test_name, test_module in tests:
            print(f"  python -m {test_module}  # {test_name}")
    
    return failed == 0

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)